<script setup lang="ts">
import qs from 'qs'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ExampleGenerate } from './evaluationDetail'
import { GetTuanEvaluationDetail, GetTuangouTuanOption, PostTuanEvaluationCreateData, PutTuanEvaluationModifyData } from '@/api/modules/tuangou'
import { GetOptionData } from '@/api/modules/subscriber'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<ExampleGenerate>({
  tuanEvaluationId: 0,
  tuanInfoId: 0,
  tuanLeaderId: 0,
  userId: 0,
  openId: '',
  nickName: '',
  avatar: '',
  contents: '',
  pictures: [],
  auditStatus: 1,
  auditReason: '',
  auditTime: '',
  viewCon: 0,
  praiseCon: 0,
  addTime: '',
})

const OptionObj = reactive({
  // TuanleaderOption: [],
  tuanInfoOptionList: [],
})

const options = ref([
  { value: 0, label: '待审核' },
  { value: 1, label: '审核成功' },
  { value: 2, label: '审核失败' },
])

const id = route.query.id as string

const rules = reactive({
  tuanInfoId: [
    { required: true, message: '请选择团购ID', trigger: 'blur' },
  ],
  tuanLeaderId: [
    { required: true, message: '请选择团长ID', trigger: 'blur' },
  ],
  orderId: [
    { required: true, message: '请输入订单ID', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '请选择昵称', trigger: 'blur' },
  ],
  userId: [
    { required: true, message: '请选择UserId', trigger: 'blur' },
  ],
  openId: [
    { required: true, message: '请选择openId', trigger: 'blur' },
  ],
  avatar: [
    { required: true, message: '请选择头像', trigger: 'blur' },
  ],
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  productCon: [
    { required: true, message: '请输入购买商品数量', trigger: 'blur' },
  ],
  recStatus: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  addTime: [
    { required: true, message: '请选择添加时间', trigger: 'blur' },
  ],
})

// 图片上传赋值
// function handleUploadSuccess(url: string, key: string) {
//   ruleForm.value[key] = url
// }

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)

      if (id) {
        // 编辑
        params.tuanEvaluationId = Number(id)
        params.pictures = (params.pictures as string[]).join(',')
        PutTuanEvaluationModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'tuangouEvaluation' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // console.log(params)
        params.pictures = (params.pictures as string[]).join(',')
        PostTuanEvaluationCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('tuanEvaluationForm')
            router.push({ name: 'tuangouEvaluation' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}
const findFrom = ref({
  UserId: '',
  SCOpenId: '',
  UserPhone: '',
  UserNickName: '',
})
const OpenIdOptionList = ref([])

const total = ref(0)
function GetOpenIdOptionList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserIdList: [findFrom.value.UserId] })),
    ...(findFrom.value.SCOpenId && ({ SCOpenId: findFrom.value.SCOpenId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.UserNickName && ({ UserNickName: findFrom.value.UserNickName })),
  }
  const parameter = qs.stringify(params)
  GetOptionData(parameter).then((res: any) => {
    if (res.statusCode === 200) {
      OpenIdOptionList.value = res.data.items
      total.value = res.data.total
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
    }
  })
}

function SetData(row: any) {
  ruleForm.value.userId = row.userId
  ruleForm.value.openId = row.scOpenId
  ruleForm.value.nickName = row.userNickName
  ruleForm.value.avatar = row.avatar
}

// 翻页
let PageSize = 20
function handleSizeChange(val: number) {
  GetOpenIdOptionList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetOpenIdOptionList(val, PageSize)
}

function GetOpenIdData() {
  GetOpenIdOptionList()
}

onMounted(async () => {
  if (id) {
    await GetTuanEvaluationDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.pictures = (res.data.pictures as string).split(',')
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('tuanEvaluationForm')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('tuanEvaluationForm', newValue)
    }
  }, { deep: true })
  const params = {
    PageIndex: 1,
    PageSize: 10000,
  }
  GetTuangouTuanOption(params).then((res: any) => {
    if (res.succeeded) {
      OptionObj.tuanInfoOptionList = res.data
    }
  })
  // GetTuanleaderOption().then((res: any) => {
  //   if (res.succeeded) {
  //     OptionObj.TuanleaderOption = res.data
  //   }
  // })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="团购信息ID" prop="tuanInfoId">
              <el-select v-model="ruleForm.tuanInfoId" placeholder="请选择团购活动" filterable>
                <el-option
                  v-for="item in (OptionObj.tuanInfoOptionList as any)"
                  :key="item.tuanInfoId"
                  :label="`${item.tuanInfoId}--${item.tuanTitle}`"
                  :value="`${item.tuanInfoId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="团长ID" prop="tuanLeaderId">
              <el-select v-model="ruleForm.tuanLeaderId" placeholder="请选择团长" filterable>
                <el-option
                  v-for="item in (OptionObj.TuanleaderOption as any)"
                  :key="item.tuanLeaderId"
                  :label="`${item.tuanLeaderId}--${item.name}`"
                  :value="`${item.tuanLeaderId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="审核状态" prop="auditStatus">
              <el-segmented
                v-model="ruleForm.auditStatus"
                size="large"
                :options="options"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="审核失败原因" prop="auditReason">
              <el-input v-model="ruleForm.auditReason" placeholder="请输入审核失败原因" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="浏览数量" prop="viewCon">
              <el-input v-model="ruleForm.viewCon" placeholder="请输入浏览数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="点赞数量" prop="praiseCon">
              <el-input v-model="ruleForm.praiseCon" placeholder="请输入点赞数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="审核时间" prop="auditTime">
              <el-date-picker
                v-model="ruleForm.auditTime"
                type="datetime"
                placeholder="请选择审核时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="发布时间" prop="addTime">
              <el-date-picker
                v-model="ruleForm.addTime"
                type="datetime"
                placeholder="请选择发布时间"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="评价内容" prop="contents">
              <el-input v-model="ruleForm.contents" placeholder="请输入评价内容" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="图片上传">
        <ElRow :gutter="20">
          <!-- <ElCol :md="24">
            <ElFormItem label="昵称" prop="nickName">
              <el-input v-model="ruleForm.nickName" placeholder="请输入昵称" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="24">
            <ElFormItem label="" prop="pictures">
              <ImagesUpload
                :size="5" :url="(ruleForm.pictures as string[])" :max="9" :ext="['jpg', 'png']"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="用户信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="UserID" prop="userId">
              <el-input v-model="ruleForm.userId" placeholder="请输入浏览数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="openId" prop="openId">
              <el-input v-model="ruleForm.openId" placeholder="请输入浏览数量" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="昵称" prop="nickName">
              <el-input v-model="ruleForm.nickName" placeholder="请选择昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="头像" prop="nickName">
              <el-image style="width: 100px; height: 100px;" :src="`${ruleForm.avatar}`" fit="fill" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="查询OpenId">
        <ElRow :gutter="20">
          <ElCol :md="5">
            <ElFormItem label="用户ID">
              <el-input v-model="findFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="OpenId">
              <el-input v-model="findFrom.SCOpenId" style="width: 300px;" placeholder="请输入OpenId" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="微信昵称">
              <el-input v-model="findFrom.UserNickName" style="width: 300px;" placeholder="请输入微信昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="授权手机号">
              <el-input v-model="findFrom.UserPhone" style="width: 300px;" placeholder="请输入授权手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="4">
            <ElFormItem label="操作">
              <ElButton @click="GetOpenIdData">
                查询
              </ElButton>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <el-table :data="OpenIdOptionList" stripe style="width: 100%;" border height="400">
              <el-table-column align="center" prop="userId" label="userId" width="150" />
              <el-table-column align="center" prop="scOpenId" label="OpenId" min-width="350" />
              <el-table-column align="center" prop="userNickName" label="微信昵称" width="300" />
              <el-table-column align="center" prop="userPhone" label="核销人手机号" width="200" />
              <el-table-column align="center" prop="address" label="操作" fixed="right" min-width="100">
                <template #default="scope">
                  <ElButton type="primary" @click="SetData(scope.row)">
                    应用
                  </ElButton>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 10px;" />
            <el-pagination
              :default-page-size="20"
              :page-sizes="[5, 10, 20, 50, 100]"
              layout="total, sizes, ->, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </elcol>
        </elrow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
